<template>
  <!-- 迎客 -->
  <view class="welcome-guest">
    <u-tabs
      :list="tabsTitle"
      :is-scroll="false"
      :current="current"
      :duration="0.3"
      height="90"
      bar-width="60"
      inactive-color="#666666"
      active-color="#FBB000"
      @change="tabsChange"
    ></u-tabs>

    <!-- 切换的内容 -->
    <view class="tab-content">
      <!-- 车牌 -->
      <view v-show="current === 0" class="car-brand">
        <view class="car-b-input-box flex flex-jc-c flex-ai-c">
          <!-- <view class="car-b-input" @click="popupKeyboardInput()">
            <view class="char-item">{{ abbrName }}</view>
          </view> -->
          <!-- 使用uView组件的源码修改的自定义 -->
          <view v-show="!isRadioCar" @click="popupKeyboardInput()">
            <message-input
              :breathe="false"
              inactive-color="#666"
              :maxlength="7"
              width="80"
              :value="carNumStr"
              disabled-keyboard
            ></message-input>
          </view>

          <view v-show="isRadioCar" @click="popupKeyboardInput()">
            <message-input
              :breathe="false"
              inactive-color="#666"
              :maxlength="8"
              width="80"
              :value="carNumStr2"
              disabled-keyboard
            ></message-input>
          </view>

          <!-- <u-keyboard
            v-model="keyboardShow"
            :show-tips="false"
            mode="car"
            :cancelBtn="false"
            :confirm-btn="false"
            :mask="false"
            @change="keyboardChange"
          ></u-keyboard> -->

          <u-popup v-model="keyboardShow" mode="bottom" :mask="false">
            <!-- 此组件为uView的u-keyboard组件内部使用的车牌组件 -->
            <i-car-keyboard
              ref="carKeyboard"
              :abc="isAbc"
              @backspace="backspaceChange"
              @change="keyboardChange"
            ></i-car-keyboard>
          </u-popup>
        </view>

        <!-- 新能源勾选、扫描 -->
        <view class="bottom-box flex flex-ai-c flex-jc-sb">
          <!-- 勾选新能源车 -->
          <label
            class="radio-car flex flex-ai-c"
            @click="isRadioCar = !isRadioCar"
          >
            <i-icon
              v-show="!isRadioCar"
              icon="icongou"
              size="38rpx"
              color="#999"
            ></i-icon>
            <i-icon
              v-show="isRadioCar"
              icon="icongouxuan"
              type="m"
              size="38rpx"
            ></i-icon>
            <text class="color-666 font-26 ml-20">新能源车</text>
          </label>

          <!-- 扫描识别 -->
          <view class="scan flex flex-ai-c" @click="goScan('shot')">
            <text class="color-666 font-26 mr-20">扫码识别</text>
            <i-icon icon="iconshouye-saoma" size="44rpx" color="#333"></i-icon>
          </view>
        </view>
      </view>

      <!-- 手机 -->
      <view v-show="current === 1" class="phone-no">
        <input
          type="number"
          v-model="phoneMobile"
          placeholder="请输入手机号"
          maxlength="11"
          class="phone-input"
          placeholder-style="font-size: 16px;"
        />
      </view>

      <!-- 订单号/码 -->
      <view v-show="current === 2" class="order-no">
        <view class="order-content flex flex-jc-sb flex-ai-c">
          <input
            type="text"
            v-model="qrNo"
            placeholder="请输入订单号/码"
            class="order-input"
          />
          <view class="line"></view>
          <view @click="scanQR">
            <i-icon
              icon="iconshouye-saoma icon-sao"
              size="44rpx"
              color="#333"
            ></i-icon>
          </view>
        </view>

        <!-- 确定按钮 -->
        <view class="btn-confirm">
          <button class="btn" @click="confirmOrder()">确定</button>
        </view>
      </view>

      <!-- 弹框提示 -->
      <u-popup
        v-model="tipShow"
        mode="center"
        :mask="false"
        width="540"
        :mask-close-able="false"
      >
        <view class="popup-content">
          <view class="title">温馨提示</view>
          <view class="content" v-if="current === 0"
            >您的门店无该车辆到店记录和订单， 将以当前车牌号创建到店单</view
          >
          <view class="content" v-if="current === 2"
            >您的门店无该车辆到店记录和订单， 请通过手机号码创建到店记录</view
          >
          <view class="btn-box">
            <button class="btn" @click="confirm">我知道了</button>
          </view>
        </view>
      </u-popup>

      <!-- 弹框提示 -->
      <u-popup
        v-model="popupShow"
        mode="center"
        :mask="false"
        width="540"
        :mask-close-able="false"
      >
        <view class="popup-content">
          <view class="title">温馨提示</view>
          <view class="content"> 是否确定以当前手机号创建到店单</view>
          <view class="btn-box flex">
            <button class="btn-left" @click="cancel">取消</button>
            <button class="btn-right" @click="okey">确定</button>
          </view>
        </view>
      </u-popup>
    </view>
  </view>
</template>

<script>
import messageInput from './components/message-input.vue'
import iCarKeyboard from '@/components/i-car-keyboard/i-car-keyboard.vue'

export default {
  components: { messageInput, iCarKeyboard },
  data() {
    return {
      // tab标题
      tabsTitle: [
        {
          name: '车牌',
        },
        {
          name: '手机',
        },
        {
          name: '订单号/码',
        },
      ],
      current: 0, // 当前的tab
      abbrName: '川', // 车牌简称
      carNum: '',
      carNumStr: '', //没有abbrName 的车牌
      carNumStr2: '', //没有abbrName 的车牌
      isRadioCar: false, // 勾选新能源车
      keyboardShow: false, // 显示车牌键盘
      phoneMobile: '', // 手机号
      qrNo: '', // 二维码id 订单号或者优惠券码
      tipShow: false, // 显示温馨提示
      scanFlag: false,
      popupShow: false, //创建到店单提示

      // 车牌键盘,是否显示英文数字键盘
      isAbc: false,
      lyBDOCR: null, //图片识别插件

      isPackage: 0, //是否为福利包 0 无 1 福利包 2 优惠券
      isNeedAddCar: false, //福利包是否需要绑定车辆
    }
  },

  computed: {
    // 车牌简称盒子的宽高
    carItemWidth() {
      return this.isRadioCar ? '80rpx' : '92rpx'
    },
  },

  watch: {
    phoneMobile(val) {
      if (val.length === 11) {
        this.getUserInfo()
      }
    },

    // 非新能源
    carNumStr(val) {
      // 如果数量到最大值，自动请求
      if (val.length === 7) {
        this.carNum = val
        this.keyboardShow = false
        this.getUserInfo()
      }
    },

    // 新能源
    carNumStr2(val) {
      // 如果数量到最大值，自动请求
      if (val.length === 8) {
        this.carNum = val
        this.keyboardShow = false
        this.getUserInfo()
      }
    },
  },

  onLoad() {
    // #ifdef APP-PLUS
    //引用插件
    this.lyBDOCR = uni.requireNativePlugin('longyoung-BDOCR')
    // #endif
  },

  onShow() {
    if (this.scanFlag) {
      this.readPic2()
    }
    this.isPackage = 0
    this.$store.commit('afterSales/resetUser')
  },

  methods: {
    //查询用户信息
    //订单状态 0、排队中 1、等待技师确认 2、取消排队 10、施工中 11、暂停施工 12、完成(未取车) 20、完成  30、取消
    getUserInfo() {
      if (this.current === 1 && !/^1[3456789]\d{9}$/.test(this.phoneMobile)) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none',
        })
        return
      }
      uni.hideKeyboard()
      this.keyboardShow = false
      let params
      if (this.isPackage) {
        params = {
          carNum: this.carNum ? this.carNum : '',
          mobile: this.carNum ? '' : this.phoneMobile,
          orderNo: '',
        }
      } else {
        params = {
          carNum: this.current === 0 ? this.carNum : '',
          mobile: this.current === 1 ? this.phoneMobile : '',
          orderNo: this.current === 2 ? this.qrNo : '',
        }
      }
      this.$api.afterSales
        .getArrivalInfo(params)
        .then((res) => {
          if (res.data.userInfo) {
            if (!res.data.userInfo.mobile && this.phoneMobile) {
              res.data.userInfo.mobile = this.phoneMobile
            }
            this.$store.commit('afterSales/setUserInfo', res.data.userInfo)
          }
          this.$store.commit('afterSales/setServeAndQueue', {
            service: res.data.service,
            queue: res.data.queue,
          })
          // 保存车辆信息
          if (res.data.carList.length) {
            if (this.isPackage === 1 && this.carNum) {
              let carList = res.data.carList.map((item) => {
                if (item.carNum === this.carNum) {
                  return item
                }
              })
              if (carList.length) {
                this.$store.commit('afterSales/setArrivalCar', carList[0])
                this.$store.commit('afterSales/setCarList', carList)
              } else {
                this.$store.commit(
                  'afterSales/setArrivalCar',
                  res.data.carList[0]
                )
                this.$store.commit('afterSales/setCarList', res.data.carList)
              }
            } else {
              this.$store.commit(
                'afterSales/setArrivalCar',
                res.data.carList[0]
              )
              this.$store.commit('afterSales/setCarList', res.data.carList)
            }
          } else if (this.current === 0) {
            this.$store.commit('afterSales/setArrivalCar', {
              carNum: this.carNum,
            })
          }
          if (res.data.arriveId && this.current !== 1) {
            //已有到店单
            this.qrNo = ''
            this.phoneMobile = ''
            this.carNum = ''
            uni.navigateTo({
              url:
                '/pages_afterSales/arrivalRecordDeatil/arrivalRecordDeatil?id=' +
                res.data.arriveId,
            })
          } else if (res.data.userInfo && res.data.userInfo.orderCount > 0) {
            //客户端已下单
            this.qrNo = ''
            this.phoneMobile = ''
            this.carNum = ''
            uni.navigateTo({
              url: '/pages_afterSales/createToStoreRecord/createToStoreRecord?isPackage=0',
            })
          } else {
            //客户端未下单
            if (this.current === 1) {
              //通过手机号查询
              this.popupShow = true
            } else if (this.isPackage) {
              // 扫码为福利包 优惠券码
              uni.navigateTo({
                url:
                  '/pages_afterSales/createToStoreRecord/createToStoreRecord?isPackage=' +
                  this.isPackage +
                  '&packageId=' +
                  this.qrNo +
                  '&addCar' +
                  this.isNeedAddCar,
              })
            } else {
              this.tipShow = true
            }
          }
        })
        .catch((err) => {
          console.log(err)
          if (this.current !== 1) {
            this.tipShow = true
          }
          if (this.current === 0) {
            this.$store.commit('afterSales/setArrivalCar', {
              carNum: this.carNum,
            })
          }
        })
    },

    // 跳转到相机扫描
    goScan(type) {
      // #ifdef APP-PLUS
      this.readPic()
      // #endif
      // #ifndef APP-PLUS
      uni.showToast({
        title: '不支持该功能',
        iocn: 'none',
      })
      // #endif
    },

    getUrlParam(url) {
      let obj = {}
      let str = url.split('?')[1].split('&')
      for (let i = 0; i < str.length; i++) {
        let a = str[i].split('=')
        obj[a[0]] = a[1]
      }
      return obj
    },

    //订单二维码扫描
    scanQR() {
      uni.scanCode({
        success: (res) => {
          let result
          if (res.result.indexOf('http') > -1) {
            result = this.getUrlParam(res.result)
          } else {
            result = JSON.parse(res.result)
          }
          if (result.state == 2) {
            //订单
            this.qrNo = result.id
            this.getUserInfo()
          } else {
            uni.showToast({
              title: '请出示维保订单核销码',
              icon: 'none',
            })
          }
        },
      })
    },

    //扫描读取图片信息(用插件读取图片信息)
    readPic() {
      uni.navigateTo({
        url: '/pages_common/ocr/ocr?type=carNumber',
        success: () => {
          uni.$once('ocr', (data) => {
            let number = data
            if (number.length > 7) {
              this.isRadioCar = true
              this.carNumStr2 = number.slice(0, 8)
            } else if (number.length) {
              this.carNumStr = number
            }
          })
        },
      })
    },

    //读取图片信息(从接口读取图片信息)
    readPic2() {
      this.scanFlag = false
      const img = uni.getStorageSync('isVal')
      if (!img) {
        return
      }
      uni.showLoading({
        title: '识别中',
      })
      const errFn = () => {
        uni.hideLoading()
        uni.showToast({
          title: '未能识别到车辆信息',
          icon: 'none',
        })
      }
      uni.compressImage({
        src: img,
        quality: 35,
        success: async (res) => {
          let imgUrl
          try {
            imgUrl = await this.$api.files.uploadImg({
              filePath: res.tempFilePath,
            })
            this.carNumberHandle(imgUrl.baseUrl + imgUrl.url, errFn)
          } catch (e) {
            errFn()
          }
        },
      })
    },

    async carNumberHandle(imgUrl, errFn) {
      try {
        let imgInfo = await this.$api.afterSales.getCarNumber({
          pic: imgUrl,
          picType: '1', //0、base64编码 1、url地址
        })
        if (imgInfo.data.status === 1) {
          errFn()
        } else {
          if (imgInfo.data[0].length > 7) {
            this.isRadioCar = true
            this.carNumStr2 = imgInfo.data[0]
          } else {
            this.carNumStr = imgInfo.data[0]
          }
          // this.abbrName = imgInfo.data[0].slice(0, 1)
          uni.hideLoading()
          setTimeout(() => {
            this.getUserInfo()
          }, 2000)
        }
      } catch (e) {
        console.log(e)
        errFn()
      }
    },

    // 监听tab切换
    tabsChange(e) {
      this.current = e
    },

    // 弹出省份简称键盘, 更换车牌省份简称
    popupKeyboardInput() {
      this.keyboardShow = true // 弹出键盘
      this.$nextTick(() => {
        this.switchKeyboard()
      })
    },

    // 自动切换键盘
    switchKeyboard() {
      // 新能源车牌
      if (this.isRadioCar) {
        this.isAbc = this.carNumStr2.length > 0
      } else {
        // 非新能源车牌
        this.isAbc = this.carNumStr.length > 0
      }
    },

    // 监听键盘选择, 选择车牌号简称
    keyboardChange(e) {
      // 如果为新能源车牌
      if (this.isRadioCar) {
        if (this.carNumStr2.length < 8) {
          this.carNumStr2 += e
        }
      } else {
        // 非新能源车牌
        if (this.carNumStr.length < 7) {
          this.carNumStr += e
        }
      }
      this.switchKeyboard()
    },

    // 退格键被点击
    backspaceChange() {
      // 如果为新能源车牌
      if (this.isRadioCar) {
        if (this.carNumStr2) {
          let str = this.carNumStr2
          this.carNumStr2 = str.substr(0, str.length - 1)
        }
      } else {
        // 非新能源车牌
        if (this.carNumStr) {
          let str = this.carNumStr
          this.carNumStr = str.substr(0, str.length - 1)
        }
      }
      this.switchKeyboard()
    },

    // 监听车牌号输入
    // carBNoInput(e) {
    //   console.log(e)
    //   let intIndex = parseInt(e.target.dataset.index)
    //   if (intIndex+1 === this.carBNo.length) {
    //     this.carBNo[intIndex].focus = false
    //     if (e.detail.value) return
    //   } else {
    //     // if (!e.detail.value) return
    //   }
    //   // 输入值后 +1，目的是焦点移到下一个输入框
    //   // 输入框删除内容 -1，则焦点退到上一个输入框
    //   let i = e.detail.value ? intIndex + 1 : intIndex - 1
    //   this.carBNo[i].focus = true
    // },

    // 订单输入确定
    confirmOrder() {
      if (!this.qrNo) {
        uni.showToast({
          title: '请输入订单号/码',
          icon: 'none',
        })
        return false
      }
      this.getUserInfo()
    },

    // 点击温馨提示的我知道了按钮
    confirm() {
      this.tipShow = false
      if (this.current === 2) {
        this.current = 1
      } else {
        this.okey()
      }
    },

    cancel() {
      this.popupShow = false
    },

    okey() {
      this.popupShow = false
      this.qrNo = ''
      this.phoneMobile = ''
      this.carNum = ''
      this.carNumStr = ''
      this.carNumStr2 = ''
      uni.navigateTo({
        url: '/pages_afterSales/createToStoreRecord/createToStoreRecord?isPackage=0',
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.welcome-guest {
  & /deep/ .u-mode-center-box {
    box-shadow: 0px 0px 32px 0px rgba(0, 0, 0, 0.14);
    border-radius: 20rpx;
  }

  button {
    background: linear-gradient(-90deg, #fbd220, #ffe23e);
    border-radius: 44rpx;

    &::after {
      border: 0;
    }
  }
}

.tab-content {
  margin-top: 30rpx;
}

// 车牌
.car-brand {
  // 车牌第一个字输入
  .car-b-input {
    position: relative;
    z-index: 99;

    .char-item {
      width: 80rpx;
      height: 80rpx;
      line-height: 80rpx;
      margin: 10rpx;
      background-color: #f4f4f4;
      border-color: #f4f4f4;
      color: rgb(96, 98, 102);
      border-radius: 6rpx;
      font-size: 44rpx;
      font-weight: bold;
      text-align: center;

      .input-content {
        width: 100%;
        height: 100%;
      }
    }
  }
}

// 新能源车勾选
.bottom-box {
  padding: 34rpx 24rpx 0;
}

@mixin inputBox {
  height: 100rpx;
  line-height: 100rpx;
  padding-left: 30rpx;
  background: #f4f4f4;
  border-radius: 10rpx;
}
// 手机
.phone-no {
  padding: 0 24rpx;
  margin: 30rpx 0;

  .phone-input {
    @include inputBox();
    font-size: 26rpx;
    color: #666;
  }
}

// 订单号
.order-no {
  padding: 0 24rpx;
  margin: 30rpx 0;

  .order-content {
    @include inputBox();

    .line {
      height: 44rpx;
      border-left: 1px solid #d0d0d0;
    }
  }

  .order-input {
    flex: 1;
    height: 100%;
    font-size: 26rpx;
    color: #666;
  }

  .icon-sao {
    margin: 0 28rpx;
  }

  // btn按钮
  .btn-confirm {
    position: fixed;
    bottom: 60rpx;
    left: 0;
    z-index: 9;
    width: 100%;
    padding: 0 24rpx;

    .btn {
      height: 88rpx;
      font-size: 32rpx;
      font-weight: 500;
      color: #333333;
    }
  }
}

// 提示弹框
.popup-content {
  padding: 30rpx 46rpx;
  text-align: center;

  .title {
    font-size: 34rpx;
    font-weight: bold;
    color: #333333;
  }

  .content {
    padding: 46rpx 0;
    font-size: 28rpx;
    font-weight: 500;
    color: #666666;
  }

  .btn-box {
    .btn {
      height: 78rpx;
      font-size: 30rpx;
      color: #333;
    }

    .btn-left {
      width: 50%;
      border-radius: 39rpx 0 0 39rpx;
      height: 78rpx;
      font-size: 30rpx;
      background: #333;
      color: #ffe23e;
    }

    .btn-right {
      width: 50%;
      border-radius: 0 39rpx 39rpx 0;
      height: 78rpx;
      font-size: 30rpx;
      color: #333;
      background: linear-gradient(-90deg, #fdd421, #ffe23e);
    }
  }
}
</style>
